package org.se.scut.hibernate.dao;

import java.util.List;
import java.util.Set;

import org.hibernate.Session;
import org.se.scut.hibernate.dao.model.Comment;
import org.se.scut.hibernate.dao.model.Picture;
import org.se.scut.hibernate.dao.utils.DAOUtils;

public class PictureDAO extends BaseDAO<Picture> {

	private static final String mostLovedsql = "select pic from Picture pic order by pic.numOfCollected desc";
	
	public Set<Comment> getComments(int pictrueID, int from, int count)
	{
		return DAOUtils.getByPagination(getAllComments(pictrueID), from, count);
	}
	
	public Set<Comment> getAllComments(int pictureID){
		Session session = HibernateSessionFactory.getSessionFactory()
				.openSession();
		try {
			session.beginTransaction();
			Picture owner = (Picture) session.get(Picture.class, pictureID);
			return owner.getComments();
		} finally {
			session.getTransaction().commit();
			session.close();
		}
	}
	
	public List<Picture> getMostCollectedPictures(int from, int count)
	{
		Session session = HibernateSessionFactory.getSessionFactory()
				.openSession();
		try {
			session.beginTransaction();
			@SuppressWarnings("unchecked")
			List<Picture> pictures = session.createQuery(mostLovedsql).setFirstResult(from)
			.setMaxResults(count).list();
			for (Picture picture : pictures) {
				picture.getComments();
			}
			return pictures;
		}finally{
			session.getTransaction().commit();
			session.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Picture> getPicturesByType(int type_id, int from, int count)
	{
		String sql = "select pic from Picture pic where pic.pictureType.id = " + type_id;
		sql += " order by pic.numOfCollected desc";
		Session session = HibernateSessionFactory.getSessionFactory()
				.openSession();
		try {
			session.beginTransaction();
			List<Picture> pictures = session.createQuery(sql).setFirstResult(from)
			.setMaxResults(count).list();
			for (Picture picture : pictures) {
				picture.getComments();
			}
			return pictures;
		}finally{
			session.getTransaction().commit();
			session.close();
		}
	}
}
